package org.efssc

def getserver(ip,credentialsid){
    def remote = [:]
    remote.name = 'dev-k8smaster-1'
    remote.host="${ip}"
    remote.port=22
    remote.allowAnyHosts=true
    withCredentials([usernamePassword(credentialsId: "${credentialsid}", passwordVariable: 'password', usernameVariable: 'userName')]) {
        remote.user = "${userName}"
        remote.password = "${password}"
    }
    return remote
    }
def deployapp(appname,namespace,imageid,publishenv){
    if("${publishenv}" == "reversion") {   //回退版本
        imageid = "oldimage"
        cmd = "python devops/apppublish/args-k8s.py -v ${imageid} -a ${appname}  -n ${namespace} -p ${publishenv}"
       // cmd = "python args-k8s.py -v ${imageid} -a ${appname} -n ${namespace} -p ${publishenv}"
    }else{
       // cmd = "python /data/script/k8s/args-k8s.py -v ${imageid} -a ${appname}  -n ${namespace} -p ${publishenv}"
        cmd = "python devops/apppublish/args-k8s.py -v ${imageid} -a ${appname}  -n ${namespace} -p ${publishenv}"
    }
    println(cmd)
    return cmd
}

def main(credentialsid, appname, namespace, imageid, publishenv){
    def envlist = ['create': '10.41.1.223','dev': '10.41.17.17', 'manage':'10.41.1.42','common':'10.41.1.14']
    def ip = envlist.findAll{
        it.key == "${publishenv}"
    }.collect{it.value}
    ips = ip[0]
    def remote = getserver(ips,"${credentialsid}")
    //command = "python args-k8s.py -a ${appname} -v ${image_tag} -r ${reponame}"
    def cmd = deployapp("${appname}","${namespace}","${imageid}", "${publishenv}")
    println(cmd)
    sh "python --version  && pip install Jinja2==2.11.3 && pip install pyyaml && pip install Markupsafe==1.1.1 && pip install pyyaml"
    sh "${cmd}"

    //def appenvs = sh returnStdout: true, script: "python devops/getenv.py"
    sshPut remote: remote, from: "devops/apppublish/yaml/${appname}.yaml", into: '/data/script/k8s/yaml/', override: true
    def result = sshCommand remote: remote, command: "kubectl apply -f /data/script/k8s/yaml/${appname}.yaml"
    println(result)
    }
